package cn.exrick.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.google.gson.Gson;

import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.mapper.TbMemberMapper;
import cn.exrick.pojo.TbMember;
import cn.exrick.pojo.front.Member;
import cn.exrick.service.LoginService;
import cn.exrick.service.MemberFrontService;
import cn.exrick.utils.QiniuUtil;
import io.rong.RongCloud;
import io.rong.models.Result;
import io.rong.models.user.UserModel;

import java.util.Date;

/**
 * @author Exrickx
 */
@Service
public class MemberFrontServiceImpl implements MemberFrontService {

    @Autowired
    private LoginService loginService;
    @Autowired
    private TbMemberMapper tbMemberMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("${rongcloud.appKey}")
    private String appKey;
    @Value("${rongcloud.appSecret}")
    private String appSecret;
    @Override
    public String imageUpload(String token,String imgData) {
        //更新缓存
        Member member=loginService.getUserByToken(token);
        //过滤data:URL
        String base64= QiniuUtil.base64Data(imgData);
        String imgPath= QiniuUtil.qiniuBase64Upload(base64);

        TbMember tbMember=tbMemberMapper.selectByPrimaryKey(member.getId());
        if(tbMember==null){
            throw new XmallException("通过id获取用户失败");
        }
        tbMember.setFile(imgPath);
        if(tbMemberMapper.updateByPrimaryKey(tbMember)!=1){
            throw new XmallException("更新用户头像失败");
        }

        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        UserModel userModel = new UserModel();
        userModel.setId(tbMember.getId().toString());
        userModel.setName(tbMember.getUsername());
        userModel.setPortrait(tbMember.getFile());
        try {
            Result result = rongCloud.user.update(userModel);
        } catch (Exception e) {
            e.printStackTrace();
        }


        member.setFile(imgPath);
        jedisClient.set("SESSION:" + token, new Gson().toJson(member));
        return imgPath;
    }

    @Override
    public String changeInfo(String token,String userName,String imageUrl, String city, String busScope, String busScopeImage) {
        //更新缓存
        Member member=loginService.getUserByToken(token);
        //过滤data:URL
//        String base64= QiniuUtil.base64Data(imgData);
//        String imgPath= QiniuUtil.qiniuBase64Upload(base64);

        TbMember tbMember=tbMemberMapper.selectByPrimaryKey(member.getId());
        if(tbMember==null){
            throw new XmallException("通过id获取用户失败");
        }
        if(StringUtils.isNotEmpty(userName)){
            tbMember.setUsername(userName);
            member.setUsername(userName);
        }
        if(StringUtils.isNotEmpty(imageUrl)){
            tbMember.setFile(imageUrl);
            member.setFile(imageUrl);
        }
        if(StringUtils.isNotEmpty(city)){
            tbMember.setCity(city);
            member.setCity(city);
        }
        if(StringUtils.isNotEmpty(busScope)){
            tbMember.setBusScope(busScope);
            member.setBusScope(busScope);
        }
        if(StringUtils.isNotEmpty(busScopeImage)){
            tbMember.setBusScopeImage(busScopeImage);
            member.setBusScopeImage(busScopeImage);
        }
        if(tbMemberMapper.updateByPrimaryKey(tbMember)!=1){
            throw new XmallException("更新失败");
        }

        if(StringUtils.isNotEmpty(userName)||StringUtils.isNotEmpty(imageUrl)){
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            UserModel userModel = new UserModel();
            userModel.setId(tbMember.getId().toString());
            userModel.setName(tbMember.getUsername());
            userModel.setPortrait(tbMember.getFile());
            try {
                Result result = rongCloud.user.update(userModel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        jedisClient.set("SESSION:" + token, new Gson().toJson(member));
        return imageUrl;
    }

    @Override
    public boolean changePassword(long userId, String newPassword) {
        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(userId);
        //MD5加密
        String md5Pass = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        tbMember.setPassword(md5Pass);
        if(tbMemberMapper.updateByPrimaryKey(tbMember)!=1){
            throw new XmallException("更新失败");
        }
        return true;
    }

	@Override
	public void updateMemCertify(long userId, int certify) {
		TbMember tbMember = tbMemberMapper.selectByPrimaryKey(userId);
		tbMember.setCertify(certify);
		if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1) {
			throw new XmallException("更新失败");
		}
	}

	@Override
	public void updateMemVip(long userId, int vip, Date expireTime) {
		TbMember tbMember = tbMemberMapper.selectByPrimaryKey(userId);
		tbMember.setVip(vip);
        tbMember.setUpdated(new Date());
        if(null != expireTime){
            tbMember.setExpireTime(expireTime);
        }
		if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1) {
			throw new XmallException("更新失败");
		}
	}

	@Override
	public void updateMemRealInfo(long userId, String realName, String idCardNo) {
		TbMember tbMember = tbMemberMapper.selectByPrimaryKey(userId);
		tbMember.setRealName(realName);
		tbMember.setIdCardNo(idCardNo);
		if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1) {
			throw new XmallException("更新失败");
		}
	}
}
